package controller

import (
	"database/sql"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/prometheus/common/log"
	"time"
)

type ShopController struct {
	beego.Controller
}

type ShopConfig struct {
	RedisAddr	string
	RedisPort	string

	DbDriver 	string
	DbUser		string
	DbPwd		string
	DbHost		string
	DbPort		string
	DbDatabases	string
	DbProtocol	string
	DbTablePre	string
}
var (
	 shopConfig = &ShopConfig{}
	 Db *sqlx.DB
	 err error
	 product []Product
	 executeResult map[string]interface{}
	 result sql.Result
	 uid int
	 searchLimit int
	 searchList []SearchList
	 keyword string
	 page int //当前页码数
	 limit int //分页数量
	 pageSize int //每页展示数量

)
func initAppConfig()*ShopConfig{
	redisAddr:=beego.AppConfig.String("redis_addr")
	redisPort:=beego.AppConfig.String("redis_port")
	dbDriver:=beego.AppConfig.String("db_driver")
	dbUser:=beego.AppConfig.String("db_user")
	dbPwd:=beego.AppConfig.String("db_pwd")
	dbHost:=beego.AppConfig.String("db_host")
	dbPort:=beego.AppConfig.String("db_port")
	dbDatabases:=beego.AppConfig.String("db_databases")
	dbProtocol:=beego.AppConfig.String("db_protocol")
	dbTablePre:=beego.AppConfig.String("db_table_pre")

	shopConfig.RedisAddr=	redisAddr
	shopConfig.RedisPort=	redisPort
	shopConfig.DbDriver	=	dbDriver
	shopConfig.DbUser	=	dbUser
	shopConfig.DbPwd	=	dbPwd
	shopConfig.DbHost	=	dbHost
	shopConfig.DbPort	=	dbPort
	shopConfig.DbDatabases	=	dbDatabases
	shopConfig.DbProtocol	=	dbProtocol
	shopConfig.DbTablePre	=	dbTablePre
	return shopConfig
}
func init(){
	initAppConfig()
	//"root:root@tcp(127.0.0.1:3306)/mini"
	sourceName:=fmt.Sprintf("%s:%s@%s(%s:%s)/%s",shopConfig.DbUser,shopConfig.DbPwd,shopConfig.DbProtocol,shopConfig.DbHost,shopConfig.DbPort,shopConfig.DbDatabases)
	Db,err=sqlx.Open(shopConfig.DbDriver,sourceName)
	if err!=nil{
		log.Info("数据库链接失败",err.Error())
		return
	}
	searchLimit=5
	pageSize	=10
}
type Product struct {
	ID int `db:"id" json:"id"`
	Name string `db:"name" json:"name"`
	Cid int `db:"cid" json:"cid"`
	PhotoLittle string `db:"photo_little" json:"photo_little"`
}
type SearchList struct {
	Uid int `db:"uid" json:"uid,omitempty"`
	Keyword string `db:"keyword" json:"keyword,omitempty"`
	Num int `db:"num" json:"num,omitempty"`
}
func  (this *ShopController)GetProduct(){
	executeResult=make(map[string]interface{})
	/*
	//executeResult["status"]=1
	//executeResult["msg"]="操作成功"
	//executeResult["data"]=[]string{"hello","world"}
	//this.Data["json"]=executeResult
	//this.ServeJSON()
	//return
	if limit,err=this.GetInt("limit",10);err!=nil{
		log.Debug("获取limit参数失败",err.Error())
		return
	}
	var product []Product
	//查询
	if err=Db.Select(&product,"select id,name,cid,photo_little from "+shopConfig.DbTablePre+"_product limit ?",limit);err!=nil{
		logs.Debug("db select err: ",err.Error())
		executeResult["status"]=0
		executeResult["msg"]="系统异常请稍后再试"
		executeResult["data"]=nil
		this.Data["json"]=executeResult
		this.ServeJSON()
		return
	}
	if len(product)>0 {
		executeResult["status"]=1
		executeResult["msg"]="操作成功"
		executeResult["data"]=product
	}else{
		executeResult["status"]=0
		executeResult["msg"]="失敗"
		executeResult["data"]=product
	}
	this.Data["json"]=executeResult
	this.ServeJSON()
	return
	 */
	//添加
	//result,err=Db.Exec("insert into mini_product  (`name`,`cid`,`photo_little`) VALUES ('测试商品','123','http://www.baidu.com')")
	//删除
	//result,err=Db.Exec("delete from mini_product where id=4562")
	//修改
	result,err=Db.Exec("update mini_product set name='修改商品名称' where id=4563")

	if err!=nil{
		logs.Debug("db select err: ",err.Error())
		executeResult["status"]=0
		executeResult["msg"]="系统异常请稍后再试"
		executeResult["data"]=nil
		this.Data["json"]=executeResult
		this.ServeJSON()
		return
	}else{
		executeResult["status"]=0
		executeResult["msg"]="插入成功"
		executeResult["data"],_=result.LastInsertId()
		this.Data["json"]=executeResult
		this.ServeJSON()
		return
	}
}

func(this * ShopController)SearchAction(){
	executeResult=make(map[string]interface{})
	searchList=nil
	product=nil
	if uid,err=this.GetInt("uid");err!=nil{
		//允许用户不登录也能看
	}
	//查询商品
	keyword =this.GetString("keyword","")
	if keyword !=""{
		if page,err=this.GetInt("p");err!=nil{
			page=1
		}
		limit =(page-1)*pageSize
		searchKeySql:=fmt.Sprintf("select id ,name,cid,photo_little from `"+shopConfig.DbTablePre+"product` where name like %s%s%s order by id desc limit %d,%d","'%",keyword,"%'",limit,pageSize)
		//log.Info(searchKeySql)
		if err=Db.Select(&product,searchKeySql);err!=nil{
			log.Info("查询商品:",err.Error())
		}
	}
	executeResult["product"]=product

	//最近搜索
	if uid>0 {
		err=Db.Select(&searchList,"SELECT `keyword`  FROM `"+shopConfig.DbTablePre+"search_history` WHERE `uid` = ?  order by addtime desc limit ? ",uid,searchLimit)
		if err!=nil{
			log.Debug("最近搜索:",err.Error())
		}
		if keyword !=""{
			var searchHistory []SearchList
			var insertStatus =0
			var updateStatus =0
			err=Db.Select(&searchHistory,"SELECT `keyword`  FROM `"+shopConfig.DbTablePre+"search_history` WHERE `uid` = ? and `keyword` =? ",uid,keyword)
			if len(searchHistory)>0{
				_,err=Db.Exec("update `mini_search_history` set num=num+1 where uid =? and keyword =?",uid,keyword)
				if err==nil{
					updateStatus=1
				}else{
					log.Info("修改:",err.Error())
				}
			}else{
				_,err=Db.Exec("insert into  `"+shopConfig.DbTablePre+"search_history`  (`uid`,`keyword`,`num`,`addtime`)value (?,?,?,?)",uid,keyword,1,time.Now().Unix())
				if err==nil{
					insertStatus=1
				}else{
					log.Info("新增:",err.Error())
				}
			}
			executeResult["insertStatus"]=insertStatus
			executeResult["updateStatus"]=updateStatus
		}
	}
	executeResult["recentKey"]=searchList
	//热门搜索
	searchList=nil
	err=Db.Select(&searchList,"select keyword ,sum(num) as num from mini_search_history group by keyword order by num  desc limit ?",searchLimit)
	if err!=nil{
		log.Info("查询热门失败:",err.Error())
	}
	executeResult["hotKey"]=searchList
	executeResult["status"]=0
	executeResult["msg"]="查询成功"
	this.Data["json"]=executeResult
	this.ServeJSON()
	return
}
func (this *ShopController)TestBeego(){
	fmt.Println("controller/shop")
	var names []string=[]string{"immoc","timor","golang"}
	this.Data ["json"]	=	names
	this.ServeJSON()
}
